package cloud.demarcia.yzcrawler;

import cloud.demarcia.yzcrawler.entities.InitInfo;
import cloud.demarcia.yzcrawler.entities.Profile;
import cloud.demarcia.yzcrawler.entities.University;
import cloud.demarcia.yzcrawler.processors.MajorListProcessor;
import cloud.demarcia.yzcrawler.processors.ProvinceProcessor;
import cloud.demarcia.yzcrawler.utils.ClockUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;

@Component
@Slf4j
public class TaskManager {


    private final ProvinceProcessor provinceProcessor;
    private final MajorListProcessor majorListProcessor;
    private final InitInfo initInfo;

    @Autowired
    public TaskManager(ProvinceProcessor provinceProcessor, MajorListProcessor majorListProcessor, InitInfo initInfo) {
        this.provinceProcessor = provinceProcessor;
        this.majorListProcessor = majorListProcessor;
        this.initInfo = initInfo;
    }

    public void run() {
        ClockUtils clockUtils1 = new ClockUtils();
        List<University> universities = generateTaskList();
        log.info(universities.size() + " items found in " + clockUtils1.durationString());
        double estimateTime = 0.26;
        log.info("starting processing, estimated time " + (int) (universities.size() * estimateTime) + " min.");
        ClockUtils clockUtils2 = new ClockUtils();
        for (University university : universities) {
            majorListProcessor.process(university);
        }
        log.info("Process finished in " + clockUtils2.durationString());
        log.info("Total time cost: " + clockUtils1.durationString());
    }

    private List<University> generateTaskList() {
        List<University> universities = new LinkedList<>();
        List<String> provinceCodes = initInfo.getProvince();
        //遍历4个专业
        Profile[] profiles = Profile.values();
        for (Profile profile : profiles) {
            log.info("finding profiles " + profile);
            //遍历初始数据列表中的省份
            for (String code : provinceCodes) {
                log.info("finding province code: " + code);
                List<String> universityNames = provinceProcessor.process(code, profile);
                //遍历所选省份中的学校
                for (String universityName : universityNames) {
                    University university = new University();
                    university.setProfile(profile);
                    university.setProvinceCode(code);
                    university.setUniversityName(universityName);
                    universities.add(university);
                }
                log.info(universityNames.size() + " universities found.");
            }
        }
        return universities;
    }
}
